<template>
  <div class="reg-field" v-loading="loading" element-loading-text="加载中...">
    <div class="header flex-justify-between">
      <div style="display: flex; gap: 5px">
        <HPlainButton @click="addField"> 添加字段 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量显示
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(4)">
                <el-icon><Switch /></el-icon>开启列表查询
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(5)">
                <el-icon><Switch /></el-icon>关闭列表查询
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(6)">
                <el-icon><Switch /></el-icon>开启列表显示
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(7)">
                <el-icon><Switch /></el-icon>关闭列表显示
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(8)">
                <el-icon><Switch /></el-icon>开启移动端显示
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(9)">
                <el-icon><Switch /></el-icon>关闭移动端显示
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div style="display: flex; gap: 5px">
        <el-select
          v-model="form.type"
          style="width: 120px"
          placeholder="选择字段类型"
          filterable
          clearable
          @change="getList"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="name"
          placeholder="字段名称"
          style="width: 100px"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
        <HButton @click="clearValue">
          <el-icon>
            <RefreshRight />
          </el-icon>
          重置
        </HButton>
      </div>
    </div>
    <div class="table-field">
      <el-table
        border
        stripe
        resizable
        @selection-change="handleChange"
        ref="tableDom"
        :data="tableData"
        height="100%"
        style="position: absolute"
      >
        <el-table-column type="selection" width="40" fixed />
        <el-table-column
          show-overflow-tooltip
          type="index"
          :index="indexMethod"
          label="序号"
          width="50"
        />
        <el-table-column show-overflow-tooltip prop="name" label="字段名称" width="150" />
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            <HStatus v-else>启用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="required" label="是否必填" width="80">
          <template #default="scope">
            <span v-if="scope.row.required">必填</span>
            <span v-else>选填</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="type" label="字段类型" width="120">
          <template #default="scope">
            <span>{{
              scope.row.type == 1
                ? '文本'
                : scope.row.type == 2
                ? '多行文本'
                : scope.row.type == 3
                ? '单选'
                : scope.row.type == 4
                ? '多选'
                : scope.row.type == 5
                ? '多图'
                : scope.row.type == 6
                ? '附件'
                : '视频'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="content" label="字段内容" min-width="120" />
        <el-table-column
          show-overflow-tooltip
          prop="listCondition"
          label="支持查询"
          width="100"
        >
          <template #default="scope">
            <div class="flex-center" style="display: flex; align-items: center; gap: 7px">
              <el-switch
                v-model="scope.row.listCondition"
                :before-change="beforeSwitchChange"
                @change="changeShow(scope.row.listCondition, scope)"
              />
              <span v-if="scope.row.listCondition">显示</span>
              <span v-else>隐藏</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="listShow" label="列表显示" width="100">
          <template #default="scope">
            <div class="flex-center" style="display: flex; align-items: center; gap: 7px">
              <el-switch
                v-model="scope.row.listShow"
                :before-change="beforeSwitchChange"
                @change="changeShow(scope.row.listShow, scope)"
              />
              <span v-if="scope.row.listShow">显示</span>
              <span v-else>隐藏</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="mobileShow" label="移动端显示" width="100">
          <template #default="scope">
            <div class="flex-center" style="display: flex; align-items: center; gap: 7px">
              <el-switch
                v-model="scope.row.mobileShow"
                :before-change="beforeSwitchChange"
                @change="changeShow(scope.row.mobileShow, scope)"
              />
              <span v-if="scope.row.mobileShow">显示</span>
              <span v-else>隐藏</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="uploadSize" label="最大尺寸(MB)" width="110" />
        <el-table-column show-overflow-tooltip prop="uploadQty" label="上传数量" width="100" />
        <el-table-column show-overflow-tooltip prop="tip" label="提示信息" width="150" />
        <el-table-column fixed="right" label="操作" width="60">
          <template #default="scope">
            <HLink @click="editField(scope.row.id)">详细</HLink>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer flex-justify-end">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </div>

    <!-- 添加/编辑  字段弹窗 -->
    <HModal v-model="addDialog" width="500">
      <template #header>
        <div class="my-header">
          <h3 class="title">{{ fieldTitle }}</h3>
        </div>
      </template>
      <div v-loading="fieldLoading">
        <div class="form-text">
          <el-form
            label-width="100"
            ref="formRef"
            :rules="rules"
            :model="form"
            class="modal_form_content"
            @validate="handleFormValidate"
          >
            <!-- 字段名称 -->
            <el-form-item
              label="字段名称"
              class="form_input_item"
              :class="{ error_form_item: !formValidateResult['name'] }"
              prop="name"
            >
              <el-input v-model="form.name" clearable placeholder="请输入名称" />
            </el-form-item>

            <!-- 字段类型 -->
            <el-form-item label="字段类型" class="form_select_item">
              <el-select v-model="form.type">
                <el-option
                  v-for="(item, index) in options"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="提示信息" class="form-item">
              <el-input v-model="form.tip" clearable placeholder="请输入提示信息" />
            </el-form-item>
            <el-form-item label="是否必填" class="form-item">
              <el-radio-group v-model="form.required">
                <el-radio :value="false">
                  <span class="bg_text">选填</span>
                </el-radio>
                <el-radio :value="true">
                  <span class="bg_text">可填</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="字段状态" class="form-item">
              <el-radio-group v-model="form.status">
                <el-radio :value="false">
                  <span class="bg_text">启用</span>
                </el-radio>
                <el-radio :value="true">
                  <span class="bg_text">禁用</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="支持查询" class="form-item">
              <el-radio-group v-model="form.listCondition">
                <el-radio :value="true">
                  <span class="bg_text">是</span>
                </el-radio>
                <el-radio :value="false">
                  <span class="bg_text">否</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="列表显示" class="form-item">
              <el-radio-group v-model="form.listShow">
                <el-radio :value="true">
                  <span class="bg_text">是</span>
                </el-radio>
                <el-radio :value="false">
                  <span class="bg_text">否</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="移动端显示" class="form-item">
              <el-radio-group v-model="form.mobileShow">
                <el-radio :value="true">
                  <span class="bg_text">是</span>
                </el-radio>
                <el-radio :value="false">
                  <span class="bg_text">否</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="字段内容"
              :required="true"
              class="form_height_22_item"
              v-if="form.type == 3 || form.type == 4"
            >
              <HPlainButton class="add" :padding-lr="6" :height="22" @click="addText"
                >+ 新增
              </HPlainButton>
            </el-form-item>
            <el-scrollbar max-height="220" v-if="form.type == 3 || form.type == 4">
              <div style="display: flex; flex-direction: column; gap: 12px">
                <div
                  v-for="(item, index) in form.contentVos"
                  :key="index"
                  style="margin-right: 10px"
                >
                  <el-form-item
                    class="form_input_item"
                    :prop="`contents[${index}][val]`"
                    :rules="rules.val"
                    :label="`${index + 1}、`"
                    :required="false"
                  >
                    <div style="display: flex; align-items: center; width: 100%; gap: 5px">
                      <el-input
                        v-model="item.val"
                        class="text-input"
                        clearable
                        placeholder="请输入字段内容"
                        maxlength="20"
                      />

                      <div style="height: 28px; line-height: 28px; width: 24px">
                        <HLink type="error" @click="handleDele(index, item)">删除</HLink>
                      </div>
                    </div>
                  </el-form-item>
                </div>
              </div>
            </el-scrollbar>

            <!-- 最大尺寸(MB) -->
            <el-form-item
              label="最大尺寸(MB)"
              v-if="form.type == 5 || form.type == 6 || form.type == 7"
              prop="uploadSize"
              class="form_input_item"
            >
              <el-input
                v-model="form.uploadSize"
                clearable
                placeholder="请输入上传的大小"
                @input="limitNum(form.uploadSize, 100)"
                type="number"
              />
            </el-form-item>

            <!-- 上传数量 -->
            <el-form-item
              label="上传数量"
              class="form_input_item"
              v-if="form.type == 5 || form.type == 6 || form.type == 7"
              prop="uploadQty"
            >
              <el-input
                v-model="form.uploadQty"
                clearable
                placeholder="请输入数量"
                maxlength="2"
                type="number"
                @input="limitNum(form.uploadQty, 10)"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footerLeft>
        <HPlainBgButton
          is-modal
          type="error"
          @click="changeAll(33)"
          v-show="fieldTitle == '编辑字段'"
          >删除
        </HPlainBgButton>
      </template>

      <template #footerRight>
        <HButton is-modal type="primary" @click="saveData(formRef, fieldFormRef)">保存</HButton>
        <HButton is-modal @click="onClose">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '../../../../../../../components/Pagination/index.vue'
  import { ref, reactive, onMounted } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    Search,
    Delete,
    Warning,
    RefreshRight,
    Switch,
    CircleCheck,
    ArrowDown,
  } from '@element-plus/icons-vue'
  import {
    getFieldList,
    saveField,
    getInfo,
    disableField,
    deleteField,
    listConditionField,
    listShowField,
    mobileShowField,
  } from '@/api/basic'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import useFormValidateService from '@/service/common/useFormValidate/useFormValidateService'

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService([{ name: 'name', isSelect: false }])

  /**
   * 弹窗关闭事件
   */
  const onClose = () => {
    resetFormValidateResult()
    addDialog.value = false
  }

  //列表序号
  const indexMethod = (index: number) => {
    return (index + 1) * 1
  }

  const name = ref('') // 字段名称
  const tableData = ref([]) // 列表数据
  const tableDom = ref() // 列表dom

  const pagination = ref() // 分页dom
  const total = ref(0) // 总数目

  const addDialog = ref(false)
  const loading = ref(false)
  const props = defineProps({
    active_name: String,
  })

  const options = ref([
    {
      value: 1,
      label: '文本',
    },
    {
      value: 2,
      label: '多行文本',
    },
    {
      value: 3,
      label: '单选',
    },
    {
      value: 4,
      label: '多选',
    },
    {
      value: 5,
      label: '多图',
    },
    {
      value: 6,
      label: '附件',
    },
    {
      value: 7,
      label: '视频',
    },
  ])

  const fieldTitle = ref('')
  const fieldLoading = ref(false)

  const form = reactive({
    id: null,
    category: 2,
    contentVos: [{ id: null, val: '' }],
    delContentVoIds: [],
    listCondition: true,
    listShow: true,
    uploadSize: null,
    mobileShow: true,
    name: '',
    required: false,
    status: false,
    tip: '',
    type: null,
    uploadQty: null,
  })

  // 表单元素
  const formRef = ref<FormInstance>()
  const fieldFormRef = ref<FormInstance>()

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入字段名称', trigger: 'blur' }],
    val: [{ required: true, message: '请输入字段内容', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
    required: [{ required: true, message: '请选择状态', trigger: 'blur' }],
    uploadSize: [
      { required: false, message: '请输入最大尺寸', trigger: 'blur' },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    uploadQty: [
      { required: false, message: '请输入上传数量', trigger: 'blur' },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
  })
  const limitNum = (val, n) => {
    if (val > n) {
      val = n
    } else if (val == 0) {
      val = 1
    }
    if (n == 100) {
      form.uploadSize = val
    } else {
      form.uploadQty = val
    }
  }
  interface switchType {
    switchStatus: boolean
  }

  let switchState = reactive<switchType>({
    switchStatus: false,
  })

  onMounted(() => {
    if (props.active_name == 'field2') {
      getList()
    }
  })

  // 重置搜索
  const clearValue = () => {
    form.type = null
    name.value = ''
    getList()
  }

  // 获取请求数据
  const getData = () => {
    return {
      category: 2,
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
      type: null,
    }
  }

  // 获取列表数据
  const getList = async () => {
    await getFieldList(getData()).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 新增字段内容
  const addText = () => {
    form.contentVos.push({ id: null, val: '' })
  }

  // 删除字段内容
  const handleDele = (index, obj) => {
    form.contentVos.splice(index, 1)
    if (obj.id) {
      form.delContentVoIds.push(obj.id)
    }
  }

  // 添加字段
  const addField = () => {
    fieldTitle.value = '添加字段'
    addDialog.value = true
    form.id = null
    form.type = null
    form.contentVos = [{ id: null, val: '' }]
    form.delContentVoIds = []
    form.listCondition = true
    form.listShow = true
    form.mobileShow = true
    form.name = ''
    form.required = false
    form.status = false
    form.tip = ''
    ;(form.uploadQty = 10), (form.uploadSize = 100)
  }

  // 编辑字段
  const editField = async (id) => {
    fieldTitle.value = '编辑字段'
    addDialog.value = true
    fieldLoading.value = true
    form.delContentVoIds = []
    await getInfo(id).then((res) => {
      fieldLoading.value = false
      form.id = res.data.data.row.id
      form.type = res.data.data.row.type
      if (res.data.data.row.contentVos.length == 0) {
        form.contentVos = [{ id: null, val: '' }]
      } else {
        form.contentVos = res.data.data.row.contentVos
      }
      form.listCondition = res.data.data.row.listCondition
      form.listShow = res.data.data.row.listShow
      form.uploadSize = res.data.data.row.uploadSize
      form.mobileShow = res.data.data.row.mobileShow
      form.name = res.data.data.row.name
      form.required = res.data.data.row.required
      form.status = res.data.data.row.status
      form.tip = res.data.data.row.tip
      form.uploadQty = res.data.data.row.uploadQty
    })
  }

  // 保存的方法
  const saveMethod = (method, data, dialog, load) => {
    load.value = true
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        dialog.value = false
        load.value = false
        getList()
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
        load.value = false
        return
      }
    })
  }

  // 保存字段
  const saveData = (formEl: FormInstance | undefined, formEl2: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        if (form.type == 3 || form.type == 4) {
          formEl2.validate((val) => {
            if (val) {
              saveMethod(saveField, form, addDialog, fieldLoading)
            }
          })
        } else {
          if (form.contentVos.length != 0) {
            form.contentVos.forEach((item) => {
              if (item?.id) {
                form.delContentVoIds.push(item?.id)
              }
            })
          }
          saveMethod(saveField, form, addDialog, fieldLoading)
        }
      }
    })
  }

  // 批量操作的方法
  const changeMethod = (type, method, arr, status, dialog, obj) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的字段`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确认${type}选中的字段?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    })
      .then(async () => {
        if (status != 3) {
          await method(arr, status).then((res: any) => {
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 2000,
            })
          })
        } else {
          await method(arr).then((res: any) => {
            if (res.data.isError)
              ElMessage({
                message: res.data.message,
                type: 'success',
                duration: 2000,
              })
            if (dialog != '') {
              dialog.value = false
            }
          })
        }
        selecttion.value = []
        tableDom.value.clearSelection()
        getList()
      })
      .catch(() => {
        if (obj.column.label == '支持查询') {
          obj.row.listCondition = !obj.row.listCondition
        }
        if (obj.column.label == '列表显示') {
          obj.row.listShow = !obj.row.listShow
        }
        if (obj.column.label == '移动端显示') {
          obj.row.mobileShow = !obj.row.mobileShow
        }
      })
  }

  // 修改字段状态
  const changeAll = (n) => {
    if (n == 1) {
      changeMethod('启用', disableField, selecttion.value, false, '', '')
    }
    if (n == 2) {
      changeMethod('禁用', disableField, selecttion.value, true, '', '')
    }
    if (n == 3) {
      changeMethod('删除', deleteField, selecttion.value, 3, '', '')
    }
    if (n == 33) {
      changeMethod('删除', deleteField, [form.id], 3, addDialog, '')
    }
    // false-不显示，true-显示
    if (n == 4) {
      changeMethod('更改', listConditionField, selecttion.value, true, '', '')
    }
    if (n == 5) {
      changeMethod('更改', listConditionField, selecttion.value, false, '', '')
    }
    if (n == 6) {
      changeMethod('更改', listShowField, selecttion.value, true, '', '')
    }
    if (n == 7) {
      changeMethod('更改', listShowField, selecttion.value, false, '', '')
    }
    if (n == 8) {
      changeMethod('更改', mobileShowField, selecttion.value, true, '', '')
    }
    if (n == 9) {
      changeMethod('更改', mobileShowField, selecttion.value, false, '', '')
    }
  }

  // 显示状态改变前判断
  const beforeSwitchChange = (val) => {
    switchState.switchStatus = true
    return switchState.switchStatus
  }

  // 显示状态改变时
  const changeShow = (val, obj) => {
    if (switchState.switchStatus) {
      if (obj.column.label == '支持查询') {
        changeMethod('更改', listConditionField, [obj.row.id], val, '', obj)
      }
      if (obj.column.label == '列表显示') {
        changeMethod('更改', listShowField, [obj.row.id], val, '', obj)
      }
      if (obj.column.label == '移动端显示') {
        changeMethod('更改', mobileShowField, [obj.row.id], val, '', obj)
      }
    }
  }

  // 返回方法
  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import '../../base/index.scss';
</style>
